package fer

import (
	"context"
	"fmt"
	"strings"
	"time"

	"gitee.com/k3x/urlx"
	"gitee.com/k3x/urlx/codec/html"
)

type Options struct {
	Currency string
	Date     time.Time
}

func FromBankOfChina(ctx context.Context, options Options) (result Rates, err error) {
	defer result.SetDuration(time.Now())
	result.From = "中国银行"
	if options.Currency == "" {
		options.Currency = "0"
	}

	if options.Date.IsZero() {
		options.Date = time.Now()
	}

	erectDate := options.Date.Format("2006-01-02")
	searchUri := "https://srh.bankofchina.com/search/whpj/searchen.jsp"

	var out []struct {
		Currency        string  `find:"td:nth-child(1)" json:"currency"` // 货币
		BuyingRate      float64 `find:"td:nth-child(2)" json:"buying_rate"`
		CashBuyingRate  float64 `find:"td:nth-child(3)" json:"cash_buying_rate"`
		SellingRate     float64 `find:"td:nth-child(4)" json:"selling_rate"`
		CashSellingRate float64 `find:"td:nth-child(5)" json:"cash_selling_rate"`
		MiddleRate      float64 `find:"td:nth-child(6)" json:"middle_rate"`
		PubTime         string  `find:"td:nth-child(7)" json:"pub_time"`
	}

	for page := 1; page <= 2; page++ {
		err = urlx.MacEdge(ctx).
			Url(searchUri).
			Method(urlx.MethodPost).
			HeaderWith(urlx.Referer(searchUri)).
			Form(strings.NewReader(fmt.Sprintf(`erectDate=%s&nothing=%s&pjname=%s&page=%d`, erectDate, erectDate, options.Currency, page))).
			Process(html.Struct(&out, "table[bgcolor$=EAEAEA] tr+tr"))
		if err != nil || len(out) != 20 {
			break
		}
	}

	result.Data = make(map[string]Rate, len(out))
	if len(out) > 0 {
		for i, r := range out {
			if i == 0 {
				result.UpdateAt, _ = time.ParseInLocation("2006.01.02 15:04:05", r.PubTime, locCST)
			}
			if _, find := result.Data[r.Currency]; find {
				break
			}
			result.Data[r.Currency] = Rate{
				Name:            GetLabel(r.Currency),
				Currency:        r.Currency,
				BuyingRate:      r.BuyingRate,
				CashBuyingRate:  r.CashBuyingRate,
				SellingRate:     r.SellingRate,
				CashSellingRate: r.CashSellingRate,
				MiddleRate:      r.MiddleRate,
			}
		}
	}
	return
}
